<template>
  <a-card :bordered="false">
    <h3>专题管理</h3>
    <LessFilter ref="filter" :type="5" @onAdd="handleAddOrEdit"  @onSearch="onSearch"></LessFilter>

    <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
      <span slot="action" slot-scope="record">

        <a-button class="btn" style="min-width: 90px;" @click="handleAddOrEdit(record)">编辑</a-button>
        <a-button class="btn" style="min-width: 90px;" @click="toDecoratePage(record)">装修</a-button>
        <a-button class="btn" style="min-width: 90px;" @click="showActivityCode(record)">投放码</a-button>
        <a-popconfirm title="确定删除当前专题吗？" ok-text="确定" cancel-text="暂不" @confirm="handleDelete(record)">
          <a-button class="btn" style="min-width: 90px;">删除</a-button>
        </a-popconfirm>
      </span>
      <div slot="state" slot-scope="text,record"><a-switch :checked="text == 1 ? true : false"  checked-children="启用" un-checked-children="禁用"  @change="onChange(record,text)" /></div>
      <div slot="storeCount" slot-scope="text,record" >
        <span v-if="record.storeType == 1">不限制门店</span>
        <span v-if="record.storeType == 2"><a @click="storeViewModal(record)">{{ text }}家门店</a></span>
      </div>
    </s-table>

    <a-modal :title="(edit ? '编辑' : '新增') + '专题'" :visible="visible" width="800px" @ok="modelFormOk" @cancel="visible = false">
      <a-spin :spinning="spinning" tip="加载中...">
        <a-form-model ref="storeForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 4 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
          <a-form-model-item label="专题名称" prop="themeName">
            <a-input allowClear v-model.trim="form.themeName" :maxLength="16" placeholder="最多输入16字"/>
          </a-form-model-item>
          <a-form-model-item label="品牌" prop="brandId">
            <a-select
              placeholder="请选择品牌"
              v-model="form.brandId"
            >
              <a-select-option :value="item.id" v-for="item in brandList" :key="item.id">
                {{ item.brandName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-item label="状态" prop="state" >
            <a-radio-group v-model="form.state">
              <a-radio :value="1">
                启用
              </a-radio>
              <a-radio :value="0">
                禁用
              </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="参活标准计算维度" required>
            <a-radio-group v-model="form.closeValueCalType" @change="resetCloseValue">
              <a-radio :value="1">
                商品品牌
              </a-radio>
              <a-radio :value="2">
                门店品牌
              </a-radio>
            </a-radio-group>
            <a-form-model-item v-if="form.closeValueCalType == 1" >
              <a-checkbox-group v-model:value="form.closeValueCalValueArr" >
                <a-checkbox v-for="item in productBrandList"  :value="item.id" :key="item.id" >{{ item.brandName }}</a-checkbox>
              </a-checkbox-group>
            </a-form-model-item>
            <a-form-model-item v-if="form.closeValueCalType == 2" >
              <a-checkbox-group v-model="form.closeValueCalValueArr" >
                <a-checkbox v-for="item in brandList" :value="item.id" :key="item.id" >{{ item.brandName }}</a-checkbox>
              </a-checkbox-group>
            </a-form-model-item>
          </a-form-item>

          <a-form-item label="参活门店" required>
            <a-radio-group v-model="form.storeType" >
              <a-radio :value="1">
                不限
              </a-radio>
              <a-radio :value="2">
                限制
              </a-radio>
            </a-radio-group>
            <a-form-model-item v-if="form.storeType == 2" >
              <a-button type="primary" @click="addStoreGroup" style="margin-left: 15px;">关联门店组</a-button>
              <a-table bordered :pagination="false" :columns="storeColumnsForForm" :data-source="form.storeGroupList" :rowKey="(record, index) => index" size="middle">
                <span slot="storeAction" slot-scope="record">
                   <a-button type="link" @click="handleStoreDelete(record)">删除</a-button>
                </span>
              </a-table>
            </a-form-model-item>
          </a-form-item>

          <a-form-model-item label="活动规则" prop="activityRules">
            <span style="display: inline-block;vertical-align: top; width: 250px;">
              <JImageUpload
                :uploadParams="getUploadParams()"
                :isMove="false"
                :isMultiple="true"
                :fileSize="10"
                :number="9"
                :accept="'image/*'"
                @fileChange="fileConsumeImgeUrlChange"
                v-model="consumeImgeUrlList"
              ></JImageUpload>
            </span>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-modal>

    <a-modal title="选择门店组" :destroyOnClose="true" :visible="storeVisible" width="800px" @ok="handleAddStoreGroup" @cancel="storeVisible = false">
      门店组名:
      <a-input-search
        :style="{width:'150px',marginBottom:'15px'}"
        placeholder="请输入门店组名"
        v-model="queryStoreParam.groupName"
        @search="onStoreSearch"
      ></a-input-search>
      门店名:
      <a-input-search
        :style="{width:'150px',marginBottom:'15px'}"
        placeholder="请输入门店名"
        v-model="queryStoreParam.storeName"
        @search="onStoreSearch"
      ></a-input-search>
      <a-button @click="resetNnStoreSearch()" style="margin-left: 20px" icon="redo">重置</a-button>
      <s-table ref="storeTable"
               size="default"
               :rowKey="record => record.id"
               :columns="storeColumns"
               :data="loadStoreData"
               :pagination="paginationProps"
               :alert="alert"
               :row-selection="rowSelection"
      >
      </s-table>
    </a-modal>
    <a-modal title="查看门店列表" :visible="storeViewVisible" width="800px" @ok="storeViewVisible = false"  @cancel="storeViewVisible = false">
      <a-table bordered :pagination="false" :columns="storeViewColumns" :data-source="storeList" :rowKey="(record, index) => index" size="middle">

      </a-table>
    </a-modal>

    <a-modal title="投放码" :visible="activityVisible" width="300px" :footer="null" @cancel="activityVisible = false">
      <a-form-item >
        <img v-if="promotionQRcode" :src="promotionQRcode" alt="投放码" style="width: 200px;height: 200px;margin-left: 30px">
        <div v-else style="width: 200px;height: 200px;"></div>
      </a-form-item>
    </a-modal>

  </a-card>
</template>
<script>
import moment from 'moment'
import { pushIfNotExist } from '@/utils/util'
import { themeList,brandList, saveOrUpdateTheme, themeDetail, removeTheme,onOrOffTheme,storeGroupList,storeList,createPromotionQRcode } from '@/api/marketingCenter/less'
import { STable } from '@/views/box/components'
import LessFilter from '../components/lessFilter'
import AFormModelItem from 'ant-design-vue/es/form-model/FormItem'
import AFormItem from 'ant-design-vue/es/form/FormItem'
import JImageUpload from '../../components/JImageUpload.vue'
import {removeArrayElement} from "../../../../utils/util";
import {log} from "dingtalk-jsapi/lib/log";

export default {
  components: {
    AFormItem,
    AFormModelItem,
    LessFilter,
    STable,
    JImageUpload,
  },
  data() {
    return {
      visible: false,
      activityVisible: false,
      storeVisible: false,
      storeViewVisible: false,
      edit: false,
      spinning: false,
      loading: false,
      imageUrl: '',
      promotionQRcode: '',
      consumeImgeUrlList: [],
      selectionRows: [],
      selectedRowKeys: [],
      storeList: [],
      brandList: [],
      productBrandList: [],
      form: {
        id: 0,
        state: 0,
        themeName: '',
        brandId: '',
        closeValueCalType: '',
        closeValueCalValueArr:[],
        storeType:'',
        activityRules: '',
        background: '',
        backgroundRelease: '',
        storeGroupList: [],
      },
      columns: [
        {
          title: '专题名称',
          align: 'center',
          dataIndex: 'themeName',
        },{
          title: '品牌',
          align: 'center',
          dataIndex: 'brandName'
        },
        {
          title: '参活门店',
          align:"center",
          dataIndex: 'storeCount',
          scopedSlots: { customRender: 'storeCount' },

        },{
          title: '活动链接',
          align:"center",
          dataIndex:"activityUrl",
        },{
          title: '状态',
          align: 'center',
          dataIndex: 'state',
          scopedSlots: { customRender: 'state' },
        },
        {
          title: '操作',
          width: '350px',
          align: 'center',
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      storeColumnsForForm: [
        {
          title: '门店组ID',
          dataIndex: 'id',
          align:"center"
        },
        {
          title: '门店组名称',
          dataIndex: 'groupName',
          align:"center"
        },
        {
          title: '操作',
          align: 'center',
          scopedSlots: { customRender: 'storeAction' }
        }
      ],
      storeColumns: [
        {
          title: '门店组名',
          align: 'center',
          dataIndex: 'groupName'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align:"center",
          customRender: (text) => {
            return moment(text).format('YYYY-MM-DD')
          }
        },
      ],
      storeViewColumns: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'storeCode'
        },{
          title: '品牌名称',
          align: 'center',
          dataIndex: 'brandName'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'storeName'
        },
      ],
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      rowSelection:{
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,

      },
      alert: { show: false, clear: () => { this.selectedRowKeys = [] } },


      queryParam: {
      },

      queryStoreParam: {
      },

      uploadData: {
      },
      rules: {
        themeName: [{ required: true, message: '请输入', trigger: 'blur' }],
        brandId: [{ required: true, message: '请选择', trigger: 'change' }],
        activityRules: [{ required: true, message: '请选择', trigger: 'change' }],
        state: [{ required: true, message: '请选择', trigger: 'change' }],
      },

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (this.requestFlag()) return
        const data = {
          "current": parameter.pageNo,
          "size": parameter.pageSize,
          ...this.queryParam
        }
        return themeList(data).then(res => {

          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      },
      //加载门店组数据
      loadStoreData: parameter => {
        const data = {
          "current": parameter.pageNo,
          "size": parameter.pageSize,
          ...this.queryStoreParam
        }
        return storeGroupList(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  activated() {
  },
  computed: {},
  mounted() {
    this.getBrandList()
  },
  watch: {
  },
  methods: {
    requestFlag() {

      const currentPathBase = '/marketingCenter/less/theme/themeList'
      const currentPath = this.$route.path
      if (!currentPath.includes(currentPathBase)) return true
      return false
    },



    //门店详情
    storeViewModal(record){
       storeList({id:record.id}).then(res => {
        if (res.code === 200) {
          if(res.data.length > 0){
            this.storeList = res.data;
            this.storeViewVisible = true;
          }else{
            this.storeList = [];
            this.storeViewVisible = true;
          }

        }
      })

    },



    // 删除
    handleDelete(record) {
      removeTheme({id: record.id}).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },


    // 新增编辑
    handleAddOrEdit(v) {
      if(v != 'null'){
        themeDetail({id: v.id}).then(res => {
          if (res.code === 200) {
            this.form.id = res.data.id;
            this.consumeImgeUrlList = res.data.activityRules ? res.data.activityRules.split(',') : []
            let aa = [];
            if(res.data.closeValueCalValue){
              res.data.closeValueCalValue.split(',').forEach(item=>{
                aa.push(Number.parseInt(item));
              })
            }
            this.form.closeValueCalValueArr = aa;
            this.form.themeName = res.data.themeName;
            this.form.state = res.data.state;
            this.form.brandId = res.data.brandId;
            this.form.brandName = res.data.brandName;
            this.form.closeValueCalType = res.data.closeValueCalType;
            this.form.storeType = res.data.storeType;
            this.form.storeGroupList = res.data.storeGroupList;
            this.form.storeGroupList.forEach(item=>{
              item.groupName = item.storeGroupName
            })
            this.visible = true;
            this.edit = true;
          } else {
            this.$message.error(res.msg || res.message)
          }
        }).catch(err => {
        })
      }else{
        this.form.id = 0;
        this.edit = false;
        this.activityRules = [];
        this.consumeImgeUrlList = [];
        this.form.storeGroupList = [];
        this.form.closeValueCalValueArr = [];
        this.form.themeName = '';
        this.form.brandId = '';
        this.form.brandName = '';
        this.form.storeType = 1;
        this.form.closeValueCalType = 1;
        this.form.state = 0;
        this.visible = true;
      }
    },

    toDecoratePage(record){
      this.$router.push(`/marketingCenter/less/decorate/${record.id}`)
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    },
    //门店组查询
    onStoreSearch(){
      this.$refs.storeTable.refresh(true)
    },
    //门店组查询重置
    resetNnStoreSearch(){
      this.queryStoreParam = {};
      this.$refs.storeTable.refresh(true)
    },

    //表单提交
    modelFormOk() {
      this.$refs.storeForm.validate(valid => {
        if (valid) {
          if(this.form.storeType == 2 && this.form.storeGroupList.length == 0){
            this.$message.error("门店组数据不能为空")
            return false;
          }
          if(this.form.closeValueCalValueArr.length == 0){
            this.$message.error("请选择参活标准计算维度品牌")
            return false;
          }

          this.form.storeGroupList.forEach(item=>{
            item.storeGroupId = item.id
          })
          const data = {
            ...this.form,
            closeValueCalValue:this.form.closeValueCalValueArr.toString(),
          }

          this.spinning = true
          saveOrUpdateTheme(data).then(res => {
            if (res.code === 200) {
              this.spinning = false
              this.visible = false
              this.$refs.table.refresh(true)
            } else {
              this.spinning = false
              this.$message.error(res.msg || res.message)
            }
          }).catch(err => {
            this.spinning = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },



    //重设计算维度值
    resetCloseValue(){
      this.form.closeValueCalValueArr = [];
    },

    // 获取品牌列表
    getBrandList() {
      brandList({
        current: 0,
        size: 99,
        state: 1
      }).then(res => {
        if (res.code === 200) {
          this.brandList = res.data.records
          this.productBrandList = res.data.records.filter(item=>{
            return item.isProductBrand == 1;
          })
        } else {
          this.$message.error(res.msg || res.message)
        }
      }).catch(err => {
      })
    },
    //状态修改
    onChange(val,text){
      onOrOffTheme({id: val.id}).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg || res.message)
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    // 添加门店组弹框
    addStoreGroup(){
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.storeVisible = true;

    },
    //添加门店组
    handleAddStoreGroup(){
      this.selectionRows.forEach(row =>
        pushIfNotExist(this.form.storeGroupList, row, 'id')
      )
      this.storeVisible = false;
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    //删除门店组
    handleStoreDelete(record){
      removeArrayElement(this.form.storeGroupList,'id',record.id);
    },
    // 图片上传

    getUploadParams() {
      return {
        actionUrl: 'https://jic.jnby.com/activity/market-act/common/upload/multipart',
        headers: {
          authorization: 'authorization-text'
        },
        uploadHost: 'https://img.bzhz.jnbygroup.com/'
      }
    },

    // 图片change
    fileConsumeImgeUrlChange(list) {
      let arr = new Array();
      if(list && list.length>0){
        list.forEach(item=>{
          arr.push(item.url)
        })
      }
      this.form.activityRules = arr.toString();
    },
    //显示投放码
    showActivityCode(record){
      this.activityVisible = true
      const { id } = record
      const data = {
        id,
      }
      createPromotionQRcode(data).then(res => {
        if (res.code === 200) {
            this.promotionQRcode = "data:image/jpg;base64,"+res.data
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img {
  display: block;
  margin: 0 auto;
  width: 120px;
  height: 120px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
}
.btn{
  margin: 4px;
}
</style>
